<template>
  <el-cascader ref="region" class="w300" @change="onChange" :options="options" :props="props" v-model="areaArry" :clearable="clearable" :placeholder="placeholder" collapse-tags></el-cascader>
</template>

<script>
import regionApi from '@/api/src/region'

export default {
  components: {},
  props: {
    value: {
      type: [Object, Array],
      default: () => {
        return []
      }
    },
    clearable: {
      type: Boolean,
      default: true
    },
    showLevel: {
      type: Number,
      default: 2,
      validator (value) {
        return [1, 2, 3].includes(value)
      }
    },
    reload: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请选择所在地区'
    },
    checkStrictly: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      areaArry: [],
      props: {
        // value: 'concatId',
        value: 'id',
        label: 'regionName',
        children: 'children',
        checkStrictly: false,
        multiple: true
      },
      options: []
    }
  },
  computed: {
    cloneValue: {
      get () {
        return this.value
      },
      set (value) {
        console.log('province:' + value)
      }
    }
  },
  watch: {
    cloneValue: {
      handler (value) {
        if (!value || value.length === 0) this.areaArry = []
      },
      immediate: true,
      deep: true
    },
    reload (val) {
      if (val) {
        if (this.value && this.value.length > 0) {
          this.backArea(this.value)
        }
        this.$emit('finish-reload')
      }
    }
  },
  created () {
    this.props.checkStrictly = this.checkStrictly
    this.getRegionTree()
  },
  mounted () { },
  methods: {
    async getRegionTree () {
      const _res = await regionApi.getList()
      const province = _res.filter(i => i.regionLevel === '1' && i.pId === '0')
      const city = _res.filter(i => i.regionLevel === '2' || i.pId === '457')
      const county = _res.filter(i => i.regionLevel === '3')
      for (let len = province.length; len--;) {
        province[len].children = city.filter(i => i.pId === province[len].id)
        for (let clen = province[len].children.length; clen--;) {
          province[len].children[clen].children = county.filter(
            i => i.pId === province[len].children[clen].id
          )
        }
      }
      this.options = province
      if (this.cloneValue && this.cloneValue.length > 0) {
        this.backArea(this.cloneValue)
      }
    },
    onChange (val) {
      const data = []
      const chosen = this.$refs.region.getCheckedNodes()
      const filterChosen = chosen.filter(i => i.checked)
      const provinceIds = filterChosen.filter(i => i.level === 1).map(i => i.value)
      const cityIds = filterChosen.filter(i => i.level === 2).map(i => i.value)
      for (let len = filterChosen.length; len--;) {
        if (filterChosen[len].level === 1) { // 已勾选省
          data.push({
            provinceId: filterChosen[len].path[0],
            provinceName: filterChosen[len].pathLabels[0],
            cityId: [],
            cityName: [],
            countyId: [],
            countyName: []
          })
        } else {
          if (!provinceIds.includes(filterChosen[len].path[0])) { // 未勾选省
            if (filterChosen[len].level === 2) { // 已勾选市
              data.push({
                provinceId: filterChosen[len].path[0],
                provinceName: filterChosen[len].pathLabels[0],
                cityId: [filterChosen[len].path[1]],
                cityName: [filterChosen[len].pathLabels[1]],
                countyId: [],
                countyName: []
              })
            } else {
              if (!cityIds.includes(filterChosen[len].path[1])) { // 未勾选市
                const pidx = data.findIndex(i => i.provinceId === filterChosen[len].path[0])
                if (pidx > -1) {
                  const cidx = data[pidx].cityId.findIndex(i => i === filterChosen[len].path[1])
                  if (cidx > -1) {
                    data[pidx] = {
                      ...data[pidx],
                      countyId: data[pidx].countyId.concat([filterChosen[len].path[2]]),
                      countyName: data[pidx].countyName.concat([filterChosen[len].pathLabels[2]])
                    }
                  } else {
                    data[pidx] = {
                      ...data[pidx],
                      cityId: data[pidx].cityId.concat([filterChosen[len].path[1]]),
                      cityName: data[pidx].cityName.concat([filterChosen[len].pathLabels[1]]),
                      countyId: data[pidx].countyId.concat([filterChosen[len].path[2]]),
                      countyName: data[pidx].countyName.concat([filterChosen[len].pathLabels[2]])
                    }
                  }
                } else {
                  data.push({
                    provinceId: filterChosen[len].path[0],
                    provinceName: filterChosen[len].pathLabels[0],
                    cityId: [filterChosen[len].path[1]],
                    cityName: [filterChosen[len].pathLabels[1]],
                    countyId: [filterChosen[len].path[2]],
                    countyName: [filterChosen[len].pathLabels[2]]
                  })
                }
              }
            }
          }
        }
      }
      setTimeout(() => {
        if (data && data.length > 0) {
          data.forEach(i => {
            i.cityId = i.cityId.join(',')
            i.cityName = i.cityName.join(',')
            i.countyId = i.countyId.join(',')
            i.countyName = i.countyName.join(',')
          })
        }
        console.log('out-data', data)
        this.$emit('input', data)
        this.$emit('change', data)
      }, 0)
    },
    backArea (area) {
      const areaList = JSON.parse(JSON.stringify(area))
      const data = []
      console.log('area', areaList)
      console.log('options', this.options)
      if (areaList && areaList.length > 0) {
        areaList.forEach(i => {
          i.cityId = i.cityId ? i.cityId.split(',').filter(i => i) : []
          i.countyId = i.countyId ? i.countyId.split(',').filter(i => i) : []
        })
        setTimeout(() => {
          for (let len = areaList.length; len--;) {
            const hasCity = areaList[len].cityId && areaList[len].cityId.length > 0
            const hasCounty = areaList[len].countyId && areaList[len].countyId.length > 0
            const province = this.options.find(i => i.id === areaList[len].provinceId)
            if (province.children && province.children.length > 0) {
              for (let clen = province.children.length; clen--;) {
                const cityId = province.children[clen].id
                const flag = (!hasCity && !hasCounty) || (hasCity && !hasCounty && areaList[len].cityId.includes(cityId))
                if (province.children[clen].children && province.children[clen].children.length > 0 && flag) { // 仅有省 || 仅有省市
                  for (let alen = province.children[clen].children.length; alen--;) {
                    data.push([
                      province.id,
                      cityId,
                      province.children[clen].children[alen].id
                    ])
                  }
                }
              }
              if (hasCounty) { // 有省市区
                for (let clen = areaList[len].cityId.length; clen--;) {
                  const cityCode = areaList[len].cityId[clen].substr(0, 4)
                  for (let alen = areaList[len].countyId.length; alen--;) {
                    const countyCode = areaList[len].countyId[alen].substr(0, 4)
                    if (cityCode === countyCode) {
                      data.push([
                        areaList[len].provinceId,
                        areaList[len].cityId[clen],
                        areaList[len].countyId[alen]
                      ])
                    }
                  }
                }
              }
            }
          }
          console.log('back-data', data)
          this.areaArry = data
        }, 0)
      } else {
        this.areaArry = []
      }
    }
  }
}
</script>

<style></style>
